package com.jjty.dataGenerator.data.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jjty.dataGenerator.data.entity.AttendanceRecord;
import com.jjty.dataGenerator.data.entity.ScCallRecord;
import com.jjty.dataGenerator.data.entity.TemperatureRecord;
import com.jjty.dataGenerator.data.entity.XykRecord;
import com.jjty.dataGenerator.data.entity.vo.GeneratedData;
import com.jjty.dataGenerator.data.entity.vo.ScCommonResponse;
import com.jjty.dataGenerator.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class DataReportService {

    @Value("${spring.datasource.url}")
    private String dbUrl;
    @Value("${spring.datasource.username}")
    private String dbUsername;
    @Value("${spring.datasource.password}")
    private String dbPassword;
    public final static String URL_PREFIX_XZN = "https://chinamobile.cinzn.com";

    public void reportCallRecordData(int numRecords) {
        List<ScCallRecord> dataList = getCallRecordDataFromDatabase(numRecords);
        for (ScCallRecord param : dataList) {
            log.info("提报数据：" + JSONObject.toJSONString(param));

            try {
                String responseBody = sendPostRequest(URL_PREFIX_XZN + "/APHealth/telephone_log", JSONObject.toJSONString(param));
                if (responseBody != null && !responseBody.isEmpty()) {
                    log.info("dataReport--->" + responseBody);
                    ScCommonResponse scCommonResponse = JSONObject.parseObject(responseBody, ScCommonResponse.class);
                    if (scCommonResponse == null) {
                        log.error("未响应推送结果！");
                        throw new ServiceException("未响应推送结果！");
                    }
                    if (scCommonResponse.getStatus() != 1) {
                        log.error(scCommonResponse.getError_msg());
                        throw new ServiceException(scCommonResponse.getError_msg());
                    }
                }
            } catch (IOException e) {
                log.error("发送请求时发生异常", e);
                throw new ServiceException("发送请求时发生异常", e);
            }
        }
    }

    private List<ScCallRecord> getCallRecordDataFromDatabase(int numRecords) {
        List<ScCallRecord> dataList = new ArrayList<>();
        String sql = "SELECT * FROM sc_call_records limit " + numRecords;
        try (Connection conn = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                ScCallRecord entity = new ScCallRecord();
                entity.setDataId(rs.getInt("data_id"));
                entity.setAppId(rs.getString("app_id"));
                entity.setUserType(rs.getString("user_type"));
                entity.setEcCode(rs.getString("ec_code"));
                entity.setUserId(rs.getString("user_id"));
                entity.setUserName(rs.getString("user_name"));
                entity.setStuNum(rs.getString("stu_num"));
                entity.setCheckTime(rs.getString("check_time"));
                entity.setTalkTime(rs.getInt("talk_time"));
                entity.setCallNumber(rs.getString("call_number"));
                entity.setTerminalId(rs.getLong("terminal_id"));
                entity.setTerminalName(rs.getString("terminal_name"));
                entity.setTerminalLocation(rs.getString("terminal_location"));
                entity.setAuthenticity(rs.getString("authenticity"));
                dataList.add(entity);
            }
        } catch (SQLException e) {
            log.error("从数据库查询数据时发生异常", e);
        }
        return dataList;
    }

    public void reportXykRecordData(int numRecords) {
        List<XykRecord> dataList = getXykRecordDataFromDatabase(numRecords);
        for (XykRecord param : dataList) {
            log.info("提报数据：" + JSONObject.toJSONString(param));

            try {
                String responseBody = sendPostRequest(URL_PREFIX_XZN + "/APHealth/campus_card_log", JSONObject.toJSONString(param));
                if (responseBody != null && !responseBody.isEmpty()) {
                    log.info("dataReport--->" + responseBody);
                    ScCommonResponse scCommonResponse = JSONObject.parseObject(responseBody, ScCommonResponse.class);
                    if (scCommonResponse == null) {
                        log.error("未响应推送结果！");
                        throw new ServiceException("未响应推送结果！");
                    }
                    if (scCommonResponse.getStatus() != 1) {
                        log.error(scCommonResponse.getError_msg());
                        throw new ServiceException(scCommonResponse.getError_msg());
                    }
                }
            } catch (IOException e) {
                log.error("发送请求时发生异常", e);
                throw new ServiceException("发送请求时发生异常", e);
            }
        }
    }

    private List<XykRecord> getXykRecordDataFromDatabase(int numRecords) {
        List<XykRecord> dataList = new ArrayList<>();
        String sql = "SELECT * FROM sc_xyk_records limit " + numRecords;
        try (Connection conn = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                XykRecord entity = new XykRecord();
                entity.setDataId(rs.getInt("data_id"));
                entity.setAppId(rs.getString("app_id"));
                entity.setAppType(rs.getString("app_type"));
                entity.setEcCode(rs.getString("ec_code"));
                entity.setSchoolName(rs.getString("school_name"));
                entity.setUserId(rs.getString("user_id"));
                entity.setStuNum(rs.getString("stu_num"));
                entity.setCardNumber(rs.getLong("card_number"));
                entity.setCardType(rs.getString("card_type"));
                entity.setBindTime(rs.getString("bind_time"));
                entity.setAuthenticity(rs.getString("authenticity"));
                dataList.add(entity);
            }
        } catch (SQLException e) {
            log.error("从数据库查询数据时发生异常", e);
        }
        return dataList;
    }

    public void reportAttendanceRecordData(int numRecords) {
        List<AttendanceRecord> dataList = getAttendanceRecordDataFromDatabase(numRecords);
        for (AttendanceRecord param : dataList) {
            log.info("提报数据：" + JSONObject.toJSONString(param));

            try {
                String responseBody = sendPostRequest(URL_PREFIX_XZN + "/APHealth/attendance_log", JSONObject.toJSONString(param));
                if (responseBody != null && !responseBody.isEmpty()) {
                    log.info("dataReport--->" + responseBody);
                    ScCommonResponse scCommonResponse = JSONObject.parseObject(responseBody, ScCommonResponse.class);
                    if (scCommonResponse == null) {
                        log.error("未响应推送结果！");
                        throw new ServiceException("未响应推送结果！");
                    }
                    if (scCommonResponse.getStatus() != 1) {
                        log.error(scCommonResponse.getError_msg());
                        throw new ServiceException(scCommonResponse.getError_msg());
                    }
                }
            } catch (IOException e) {
                log.error("发送请求时发生异常", e);
                throw new ServiceException("发送请求时发生异常", e);
            }
        }
    }

    private List<AttendanceRecord> getAttendanceRecordDataFromDatabase(int numRecords) {
        List<AttendanceRecord> dataList = new ArrayList<>();
        String sql = "SELECT * FROM sc_attendance_records limit " + numRecords;
        try (Connection conn = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                AttendanceRecord entity = new AttendanceRecord();
                entity.setDataId(rs.getInt("data_id"));
                entity.setAppId(rs.getString("app_id"));
                entity.setUserType(rs.getString("user_type"));
                entity.setEcCode(rs.getString("ec_code"));
                entity.setUserId(rs.getString("user_id"));
                entity.setUserName(rs.getString("user_name"));
                entity.setStuNum(rs.getString("stu_num"));
                entity.setCheckTime(rs.getString("check_time"));
                entity.setTerminalId(rs.getLong("terminal_id"));
                entity.setTerminalName(rs.getString("terminal_name"));
                entity.setTerminalLocation(rs.getString("terminal_location"));
                entity.setTerminalType(rs.getString("terminal_type"));
                entity.setAuthenticity(rs.getString("authenticity"));
                dataList.add(entity);
            }
        } catch (SQLException e) {
            log.error("从数据库查询数据时发生异常", e);
        }
        return dataList;
    }

    public void reportTemperatureRecordData(int numRecords) {
        List<TemperatureRecord> dataList = getTemperatureRecordDataFromDatabase(numRecords);
        for (TemperatureRecord param : dataList) {
            log.info("提报数据：" + JSONObject.toJSONString(param));

            try {
                String responseBody = sendPostRequest(URL_PREFIX_XZN + "/APHealth/temperature_log", JSONObject.toJSONString(param));
                if (responseBody != null && !responseBody.isEmpty()) {
                    log.info("dataReport--->" + responseBody);
                    ScCommonResponse scCommonResponse = JSONObject.parseObject(responseBody, ScCommonResponse.class);
                    if (scCommonResponse == null) {
                        log.error("未响应推送结果！");
                        throw new ServiceException("未响应推送结果！");
                    }
                    if (scCommonResponse.getStatus() != 1) {
                        log.error(scCommonResponse.getError_msg());
                        throw new ServiceException(scCommonResponse.getError_msg());
                    }
                }
            } catch (IOException e) {
                log.error("发送请求时发生异常", e);
                throw new ServiceException("发送请求时发生异常", e);
            }
        }
    }

    private List<TemperatureRecord> getTemperatureRecordDataFromDatabase(int numRecords) {
        List<TemperatureRecord> dataList = new ArrayList<>();
        String sql = "SELECT * FROM sc_temperature_records limit " + numRecords;
        try (Connection conn = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                TemperatureRecord entity = new TemperatureRecord();
                entity.setDataId(rs.getInt("data_id"));
                entity.setAppId(rs.getString("app_id"));
                entity.setUserType(rs.getString("user_type"));
                entity.setEcCode(rs.getString("ec_code"));
                entity.setUserId(rs.getString("user_id"));
                entity.setUserName(rs.getString("user_name"));
                entity.setStuNum(rs.getString("stu_num"));
                entity.setCheckTime(rs.getString("check_time"));
                entity.setTerminalId(rs.getLong("terminal_id"));
                entity.setTerminalName(rs.getString("terminal_name"));
                entity.setTerminalLocation(rs.getString("terminal_location"));
                entity.setTemperature(rs.getDouble("temperature"));
                entity.setAuthenticity(rs.getString("authenticity"));
                dataList.add(entity);
            }
        } catch (SQLException e) {
            log.error("从数据库查询数据时发生异常", e);
        }
        return dataList;
    }

    private String sendPostRequest(String url, String jsonBody) throws IOException {
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setEntity(new StringEntity(jsonBody, "UTF-8"));

        HttpResponse response = httpClient.execute(httpPost);
        return EntityUtils.toString(response.getEntity(), "UTF-8");
    }

    public void reportData(String dataType, String url) {
        List<JSONObject> dataList = getDataFromDatabase(dataType);
        Logger log = LoggerFactory.getLogger(getClass());
        int totalCount = 0;
        int successCount = 0;
        int failureCount = 0;

        for (JSONObject param : dataList) {
            totalCount++;
            log.info("提报数据：" + JSONObject.toJSONString(param));
            try {
                String responseBody = sendPostRequest(url, JSONObject.toJSONString(param));
                if (responseBody != null && !responseBody.isEmpty()) {
                    log.info("dataReport--->" + responseBody);
                    ScCommonResponse scCommonResponse = JSONObject.parseObject(responseBody, ScCommonResponse.class);
                    if (scCommonResponse == null) {
                        log.error("未响应推送结果！跳过数据：" + JSONObject.toJSONString(param));
                        failureCount++;
                        continue;
                    }
                    if (scCommonResponse.getStatus() != 1) {
                        log.error("上报失败，错误信息：" + scCommonResponse.getError_msg() + "，跳过数据：" + JSONObject.toJSONString(param));
                        failureCount++;
                    } else {
                        successCount++;
                    }
                } else {
                    log.error("上报失败，无响应内容，跳过数据：" + JSONObject.toJSONString(param));
                    failureCount++;
                }
            } catch (IOException e) {
                log.error("发送请求时发生异常，跳过数据：" + JSONObject.toJSONString(param), e);
                failureCount++;
            }
        }

        // 记录总体统计信息
        log.info("数据上报完成！总数据量：" + totalCount + "，成功：" + successCount + "，失败：" + failureCount);
    }

    private List<JSONObject> getDataFromDatabase( String dataType) {
        List<JSONObject> dataList = new ArrayList<>();
        String sql = "SELECT data_id, data_fields FROM generated_data WHERE data_type = '" + dataType + "'";
        Logger log = LoggerFactory.getLogger(getClass());
        try (Connection conn = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                // 从结果集中获取 id 字段的值
                int dataId = rs.getInt("data_id");
                // 从结果集中获取 JSON 字符串
                String jsonStr = rs.getString("data_fields");
                if (jsonStr != null) {
                    // 将 JSON 字符串解析为 JSONObject
                    JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                    // 将 id 字段添加到 JSONObject 中
                    jsonObject.put("dataId", dataId);
                    dataList.add(jsonObject);
                }
            }
        } catch (Exception e) {
            log.error("从数据库查询数据时发生异常", e);
        }
        return dataList;
    }
}
